//
//  XPPXcodeRegisterMenuItem.m
//  XPPXcodePlugin
//
//  Created by yoyokko on 10-4-22.
//  Copyright 2010 yoyokko@gmail.com. All rights reserved.
//

#import "XPPXcodeRegisterMenuItem.h"
#import "XPPDSAVerifier.h"

#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>

// Returns the serial number as a CFString.
// It is the caller's responsibility to release the returned CFString when done with it.
void CopySerialNumber(CFStringRef *serialNumber)
{
    if (serialNumber != NULL) {
        *serialNumber = NULL;
		
        io_service_t    platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
																	 IOServiceMatching("IOPlatformExpertDevice"));
		
        if (platformExpert) {
            CFTypeRef serialNumberAsCFString =
			IORegistryEntryCreateCFProperty(platformExpert,
											CFSTR(kIOPlatformSerialNumberKey),
											kCFAllocatorDefault, 0);
            if (serialNumberAsCFString) {
                *serialNumber = serialNumberAsCFString;
            }
			
            IOObjectRelease(platformExpert);
        }
    }
}

@implementation XPPXcodeRegisterMenuItem
+ (void)load {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	//[XPPXcodePlugin registerMenuItem:[[[self alloc] init] autorelease]];
	[pool release];
}

- (id) init
{
	if (self = [super init]) {
		[NSBundle loadNibNamed:@"XPPRegisterInput" owner:self];
	}
	return self;
}

- (NSString*)title {
	return @"Register XPP Xcode Plugin";
}

- (void)action:(id)sender {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	CFStringRef serialNumber;
	CopySerialNumber(&serialNumber);
	[productIDField setStringValue:(NSString *)serialNumber];
	CFRelease(serialNumber);
	NSString *userName = [defaults stringForKey:@"RegisterUserName"];
	NSString *code = [defaults stringForKey:@"RegisterCode"];
	[userNameField setStringValue:(userName ? userName:@"")];
	[registerCodeField setStringValue:(code ? code:@"")];
	
	if ([XPPXcodeRegisterMenuItem isRegistered]){
		[registerStatusField setStringValue:@"Registered!"];
	}else {
		[registerStatusField setStringValue:@"Not Registered!"];
	}
	
	[NSApp runModalForWindow:registerWindow];
}

- (NSMenu*)insertionMenu {
	NSMenu *rootMenu = [NSApp mainMenu];
	NSMenuItem *appleMenuItem = [rootMenu itemAtIndex:0];
	return [appleMenuItem submenu];
}

- (int)insertionIndex {
	return 3;
}

- (IBAction) buyNow:(id) sender
{
	NSRunAlertPanel(@"Infomation", @"After payment, please provide your product ID number & user name\nand mail to yoyokko@gmail.com", 
					@"Buy", @"", @"");
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://yoyokko.gicp.net/xpp/index.html"]];
}

- (IBAction) closeRegisterWindow:(id) sender
{
	[NSApp stopModal];
	[registerWindow orderOut:self];
}

- (void)controlTextDidChange:(NSNotification *)aNotification
{
	NSString *encodedSignature = [registerCodeField stringValue];
	NSString *filePath = [[XPPXcodePlugin pluginBundle] pathForResource:@"license" ofType:@"key"];
	if ([XPPDSAVerifier validatePath:filePath withEncodedDSASignature:encodedSignature withPublicDSAKey:publicDSAKey]) {
		[registerStatusField setStringValue:@"Registered!"];
		
	}else {
		[registerStatusField setStringValue:@"Not Registered!"];
	}
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setValue:[userNameField stringValue] forKey:@"RegisterUserName"];
	[defaults setValue:[registerCodeField stringValue] forKey:@"RegisterCode"];
	[defaults synchronize];
}

+ (BOOL) isRegistered
{
//	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//	
//	if (![defaults stringForKey:@"RegisterUserName"])
//		return NO;
//	
//	if (![defaults stringForKey:@"RegisterCode"])
//		return NO;
//	
//	NSString *filePath = [[XPPXcodePlugin pluginBundle] pathForResource:@"license" ofType:@"key"];
//	if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
//		return NO;
//	
//	NSString *encodedSignature = [defaults stringForKey:@"RegisterCode"];
//	if ([XPPDSAVerifier validatePath:filePath withEncodedDSASignature:encodedSignature withPublicDSAKey:publicDSAKey]) {
//		return YES;
//	}else {
//		return NO;
//	}
	
	return YES;
}

@end

